<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<script src="analytics.js"></script>
</head>
<body>
<script>

var screenshot = {
  tab: 0,
  canvas: document.createElement("canvas"),
  startX: 0,
  startY: 0,
  scrollX: 0,
  scrollY: 0,
  docHeight: 0,
  docWidth: 0,
  visibleWidth: 0,
  visibleHeight: 0,
  scrollXCount: 0,
  scrollYCount: 0,
  scrollBarX: 17,
  scrollBarY: 17,
  captureStatus: true,

	addMessageListener : function() {
		chrome.extension.onRequest.addListener(function(request, sender, response) {
			if( request.msg ){
				switch(request.msg) {
					case 'capture_selected':
						screenshot.captureSelected();
						break;
				}
			}
		});
	},

  /**
  * Send the Message to content-script
  */
  sendMessage: function(message, callback) {
    chrome.tabs.getSelected(null, function(tab) {
      chrome.tabs.sendRequest(tab.id, message, callback);
    });
  },

	showSelectionArea: function() {
		screenshot.sendMessage({msg: 'show_selection_area'}, null);
	},
	
	shareLink : function(){
		screenshot.sendMessage({msg: 'share_link'}, null);		
	},
  captureSelected: function() {
    screenshot.sendMessage({msg: 'capture_selected'},
        screenshot.onResponseVisibleSize);
  },

  onResponseVisibleSize : function(response) {
    switch(response.msg) {
      case 'scroll_init_done':
        screenshot.startX = response.startX,
        screenshot.startY = response.startY,
        screenshot.scrollX = response.scrollX,
        screenshot.scrollY = response.scrollY,
        screenshot.canvas.width = response.canvasWidth;
        screenshot.canvas.height = response.canvasHeight;
        screenshot.visibleHeight = response.visibleHeight,
        screenshot.visibleWidth = response.visibleWidth,
        screenshot.scrollXCount = response.scrollXCount;
        screenshot.scrollYCount = response.scrollYCount;
        screenshot.docWidth = response.docWidth;
        screenshot.docHeight = response.docHeight;
        screenshot.zoom = response.zoom;
        setTimeout("screenshot.captureAndScroll()", 100);
        break;
      case 'scroll_next_done':
        screenshot.scrollXCount = response.scrollXCount;
        screenshot.scrollYCount = response.scrollYCount;
        setTimeout("screenshot.captureAndScroll()", 100);
        break;
      case 'scroll_finished':
        screenshot.captureAndScrollDone();
        break;
    }
  },

  /**
  * Use the drawImage method to stitching images, and render to canvas
  */
	captureAndScroll : function() {
		var formatParam  = localStorage.screenshootQuality || 'png';

		chrome.tabs.captureVisibleTab(null, {format: formatParam, quality: 50}, function(data) {
			var image = new Image();

			image.onload = function() {
				var context = screenshot.canvas.getContext('2d'),
					width = 0,
					height = 0;
				// Get scroll bar's width.
				screenshot.scrollBarY = 
					screenshot.visibleHeight < screenshot.docHeight ? 17 : 0;
				screenshot.scrollBarX = 
					screenshot.visibleWidth < screenshot.docWidth ? 17 : 0;

				// Get visible width and height of capture result.
				var visibleWidth = 
					(image.width - screenshot.scrollBarY < screenshot.canvas.width ?
					image.width - screenshot.scrollBarY : screenshot.canvas.width);
				var visibleHeight = 
					(image.height - screenshot.scrollBarX < screenshot.canvas.height ?
					image.height - screenshot.scrollBarX : screenshot.canvas.height);

				// Get region capture start x coordinate.
				var zoom = screenshot.zoom,
					x1 = screenshot.startX - Math.round(screenshot.scrollX * zoom),
					x2 = 0,
					y1 = screenshot.startY - Math.round(screenshot.scrollY * zoom),
					y2 = 0;
				if ((screenshot.scrollYCount + 1) * visibleWidth >
					screenshot.canvas.width) {
					width = screenshot.canvas.width % visibleWidth ;
					x1 = (screenshot.scrollYCount + 1) * visibleWidth -
					  screenshot.canvas.width + screenshot.startX - screenshot.scrollX;
				} else {
					width = visibleWidth;
				}
				
				if ((screenshot.scrollXCount + 1) * visibleHeight >
					screenshot.canvas.height) {
				  height = screenshot.canvas.height % visibleHeight;
				  if ((screenshot.scrollXCount + 1) * visibleHeight + 
					  screenshot.scrollY < screenshot.docHeight) {
					y1 = 0;
				  } else {
					y1 = (screenshot.scrollXCount + 1) * visibleHeight + 
						screenshot.scrollY - screenshot.docHeight ;
				  }

				} else {
				  height = visibleHeight ;
				}
				x2 = screenshot.scrollYCount * visibleWidth;
				y2 = screenshot.scrollXCount * visibleHeight;
				context.drawImage(image, x1, y1, width, height, x2, y2, width, height);
				screenshot.sendMessage({msg: 'scroll_next', visibleWidth: visibleWidth,
					visibleHeight: visibleHeight}, screenshot.onResponseVisibleSize);
			};
			image.src = data;
		});
	},

	captureAndScrollDone : function() {
		screenshot.f2quTransportData();
	},

	f2quTransportData : function (){
		var data = screenshot.canvas.toDataURL('image/png');
		screenshot.sendMessage({msg: 'transport_data', data: data});
	},

	init : function() {
		screenshot.addMessageListener();
	}
};
//
screenshot.init();

function checkAndSendStatus(){
	chrome.cookies.getAll({url:"http://42qu.com"},function(cookies){
		for( var i=0; i<cookies.length; i++ ){
			var cookie = cookies[i];
			if( cookie.name == 'S' && cookie.value && cookie.value!='' ){
				screenshot.sendMessage({
					'msg': 'get_user_info',
					'tag_id': localStorage.getItem('f2qu_tag_id'),
					'f2qu_user_info':localStorage.getItem('f2qu_user_info')
				})
			}
		}
	})
}

chrome.tabs.onUpdated.addListener(function (){
	checkAndSendStatus()
})

if(typeof(chrome.tabs.onActivated) != 'undefined'){
	chrome.tabs.onActivated.addListener(function (){
		checkAndSendStatus()
	})
} else if(typeof(chrome.tabs.onActiveChanged) != 'undefined'){
	chrome.tabs.onActiveChanged.addListener(function (){
		checkAndSendStatus()
	})
} else{
	screenshot.sendMessage({'msg':'version_low_hint'})
}


chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
	if(request.localstorage == 'opts'){
		sendResponse({
			opts: {
				'picsize':localStorage['picsize'],
				'showhow':localStorage['showhow'],
				'hidedirpic':localStorage['hidedirpic']
			}
		})
	}else if(request.msg == 'save_option_data'){
		var data = JSON.parse(request.option_data)
		if(data){
			localStorage.setItem('picsize',data.picsize)
			localStorage.setItem('showhow',data.showhow)
			localStorage.setItem('hidedirpic',data.hidedirpic)		
		}
	}
	else if(request.msg == 'do_with_img'){
		var src = request.src
		if(src.indexOf('data:image/png;base64,')<0){
			var img = new Image();
			img.onload = function() {
				var img_url = getBase64Image(img);
				sendResponse({'img_url': img_url})
			};
			if(src.indexOf('http://')<0){
				var a = src.indexOf('//'),
					b = a<0?src:src.substr(a)
				src = 'http://' + b;
			}
			img.src = src;
		} else{
			sendResponse({'img_url': src})
		}
	}
	else if(request.msg == 'save_tag_id'){
		localStorage.setItem("f2qu_tag_id",request.tag_id)
	}
	else if(request.msg == 'save_user_info'){
		localStorage.setItem("f2qu_user_info",request.f2qu_user_info)
	}
	else if(request.msg == 'get_account'){
		sendResponse({'user':localStorage.getItem('f2qu_user_info')})
	}
	else if(request.msg == 'refresh_account'){
		localStorage.removeItem('f2qu_user_info')
		localStorage.removeItem('f2qu_tag_id')

		sendResponse({})
	}
	else if(request.msg =='check_cookie'){
		var ctrl = false
		chrome.cookies.getAll({url:"http://42qu.com"},function(cookies){
			for( var i=0; i<cookies.length; i++ ){
				var cookie = cookies[i];
				if( cookie.name == 'S' && cookie.value && cookie.value!='' ){
					ctrl = true
				}
			}
			sendResponse({'ctrl': ctrl})
		})
	}
})

function getBase64Image(img) {
	// Create an empty canvas element
	var canvas = document.createElement("canvas");
	canvas.width = GetImageWidth(img);
	canvas.height = GetImageHeight(img);

	// Copy the image contents to the canvas
	var ctx = canvas.getContext("2d");
	ctx.drawImage(img, 0, 0);

	// Get the data-URL formatted image
	// Firefox supports PNG and JPEG. You could check img.src to
	// guess the original format, but be aware the using "image/jpg"
	// will re-encode the image.
	return canvas.toDataURL("image/png");

//			return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

function GetImageWidth(oImage){
	var OriginImage=new Image();
	if(OriginImage.src!=oImage.src)OriginImage.src=oImage.src;
	return OriginImage.width;
}
function GetImageHeight(oImage){
	var OriginImage=new Image();
	if(OriginImage.src!=oImage.src)OriginImage.src=oImage.src;
	return OriginImage.height;
}

//右键菜单 收集功能
chrome.contextMenus.create({
	title : "分享到42区", 
	contexts: ["image","selection"],
	onclick : share_click_image
})


function share_click_image(a){
	if(a.mediaType == "image") {
		screenshot.sendMessage({msg: 'right_click_image','src':a.srcUrl});
	}else{
		screenshot.sendMessage({msg: 'share_link',txt:encodeURIComponent(a.selectionText)});
	}
}

</script>
</body>
</html>
